<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button type="primary" @click="clickUpdate(1)">添加</el-button>
            <el-button type="default" plain @click="allDel">批量删除</el-button>
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="handleAllSelected"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="price_id" label="ID" width="80"></el-table-column>
            <el-table-column prop="product_amount" label="供应价最小金额" min-width="140"></el-table-column>
            <el-table-column prop="price" label="价格涨跌" min-width="120"></el-table-column>
            <el-table-column prop="special_price" label="特惠涨跌" min-width="120"></el-table-column>
            <el-table-column prop="seckill_price" label="秒杀价涨跌" min-width="130"></el-table-column>
            <el-table-column prop="updated_at_label" label="更新时间" width="170"></el-table-column>
            <el-table-column prop="created_at_label" label="添加时间" width="170"></el-table-column>
            <el-table-column label="操作" width="230" class-name="operation-nav" fixed="right">
                <template #default="{ row }">
                    <el-button class="theme-btn" link type="primary" @click="clickUpdate(2, row)">编辑</el-button>
                    <el-button class="theme-btn" link type="primary" @click="clickSetup(row)">设置会员涨跌</el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDelete(row)">
                        <template #reference>
                            <el-button class="theme-btn" link type="primary">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>

        <!-- 添加/编辑 -->
        <el-dialog
            v-model="dialogZd"
            :title="classType == 1 ? '添加商品涨跌' : '编辑商品涨跌'"
            width="620px"
            :append-to-body="true"
            :destroy-on-close="true"
            :close-on-click-modal="false"
            @close="closeAddZd"
        >
            <el-form ref="ruleZdRef" :model="ruleZdForm" :rules="ruleCheckZd" label-width="160px">
                <el-form-item label="供应价最小金额" prop="min_price">
                    <el-input
                        v-model.trim="ruleZdForm.min_price"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入供应价最小金额"
                    />
                </el-form-item>
                <el-form-item label="价格涨跌" prop="price_zd">
                    <el-input v-model.trim="ruleZdForm.price_zd" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入价格涨跌" />
                </el-form-item>
                <el-form-item label="特惠涨跌" prop="special_zd">
                    <el-input
                        v-model.trim="ruleZdForm.special_zd"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入特惠涨跌"
                    />
                </el-form-item>
                <el-form-item label="秒杀价涨跌" prop="seckill_price">
                    <el-input
                        v-model.trim="ruleZdForm.seckill_price"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入秒杀价涨跌"
                    />
                </el-form-item>
                <el-form-item>
                    <div class="flexs" style="margin-top: 20px">
                        <el-button type="primary" :loading="form_loading" @click="submitZdForm(ruleZdRef)">
                            {{ classType == 1 ? "确认添加" : "确认修改" }}
                        </el-button>
                        <el-button @click="resetZdForm(ruleZdRef)">重置</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 设置会员涨跌 -->
        <el-dialog
            v-model="dialogLevel"
            title="设置会员涨跌"
            width="620px"
            :append-to-body="true"
            :destroy-on-close="true"
            :close-on-click-modal="false"
        >
            <div>
                <cell-tip tip="注意：会员等级涨跌价不得超过已设置的价格涨跌价，否则收益呈负数！" bottom="20px" />
                <detail-item title="价格涨跌价" :value="itemObjs.price" align-item="center" />
                <detail-item bottom="16px" :title="item.level_name" v-for="(item, index) in levelArrs" :key="index">
                    <el-input
                        v-model.trim="item.discount"
                        class="detail-input"
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        clearable
                        placeholder="请输入会员涨跌价"
                        style="width: 300px"
                    />
                </detail-item>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" :loading="form_loading" @click="handleSetupLevel">确认</el-button>
                    <el-button @click="dialogLevel = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, reactive, onBeforeUnmount } from "vue"
import OneLoad from "@mixins/one-load"
import CellTip from "@components/cell-tip.vue"
import DetailItem from "@components/DetailItem.vue"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getList()
})

onBeforeUnmount(() => {
    itemObjs.value = null
    
})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, pubParams, getdata } = OneLoad()
// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
    }
    getdata("product/price/index", params)
}

/**
 * 添加/编辑
 * @property {Boolean} dialogZd 添加/编辑弹窗状态
 * @property {Boolean} form_loading 提交按钮状态
 * @property {Number} classType 弹窗类型，1是添加，2是编辑
 * @property {Array} ruleZdRef 表单规则
 * @property {Object} ruleZdForm  表单字段
 * @property {Object} ruleCheckZd  表单提示
 * @property {Function} submitZdForm 提交表单
 * @property {Function} addZd 添加分类
 * @property {Function} closeAddZd 关闭弹窗
 */
const dialogZd = ref(false)
const form_loading = ref(false)
const classType = ref(1)
const ruleZdRef = ref(null)
const ruleZdForm = reactive({
    price_id: "",
    min_price: "",
    price_zd: "",
    special_zd: "",
    seckill_price: "",
})
const ruleCheckZd = reactive({
    min_price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    price_zd: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    special_zd: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    seckill_price: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
})
const submitZdForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let data = {
                product_amount: ruleZdForm.min_price, // 供应价最小金额
                price: ruleZdForm.price_zd, // 价格涨跌
                special_price: ruleZdForm.special_zd, // 特惠涨跌
                seckill_price: ruleZdForm.seckill_price, // 秒杀价格涨跌
            }
            if (classType.value == 2) {
                data.price_id = ruleZdForm.price_id
            }
            let url = classType.value == 1 ? "product/price/add" : "product/price/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogZd.value = false
                        proxy.$message({ message: `${classType.value == 1 ? '添加成功！' : '编辑成功！'}`, type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetZdForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

// 添加/编辑
const clickUpdate = (type, row) => {
    classType.value = type
    dialogZd.value = true
    if (type == 2) {
        setTimeout(() => {
            ruleZdForm.price_id = row.price_id
            ruleZdForm.min_price = row.product_amount
            ruleZdForm.price_zd = row.price
            ruleZdForm.special_zd = row.special_price
            ruleZdForm.seckill_price = row.seckill_price
        }, 50)
    }
}
const closeAddZd = () => {
    dialogZd.value = false
    resetZdForm(ruleZdRef.value)
}

// 设置会员等级折扣
const dialogLevel = ref(false)
const itemObjs = ref({})
const levelArrs = ref([])
const clickSetup = (row) => {
    dialogLevel.value = true
    itemObjs.value = row
    console.log('itemObjs.value',itemObjs.value);
    getLevel(row.price_id)
}
const handleSetupLevel = () => {
    for (let i = 0; i < levelArrs.value.length; i++) {
        if (levelArrs.value[i].discount === "") {
            proxy.$message({ message: "请完善会员等级折扣", type: "warning" })
            return
        }
    }
    let arrs = []
    levelArrs.value.map((item) => {
        arrs.push({
            grade_id: item.grade_id,
            discount: item.discount,
        })
    })
    form_loading.value = true
    proxy.$axios
        .post("product/price/discount", {
            price_id: itemObjs.value.price_id,
            user_grade: arrs,
        })
        .then((res) => {
            form_loading.value = false
            if (res.data.code == 0) {
                dialogLevel.value = false
                proxy.$message({ message: "设置折扣成功！", type: "success" })
                pubParams(getList)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {
            form_loading.value = false
        })
}
function getLevel(id) {
    proxy.$axios
        .get("product/price/discount", {
            params: {
                price_id: id,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                levelArrs.value = res.data.data
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

// 删除单个
const handleDelete = (row) => {
    postDel(row.price_id)
}
// 删除多个
const ids = ref([])
const handleAllSelected = (val) => {
    let arrs = []
    for (let i = 0; i < val.length; i++) {
        arrs.push(val[i].price_id)
    }
    ids.value = arrs
}
const allDel = () => {
    if (ids.value.length == 0) {
        proxy.$message({ message: "请选择需要删除的数据", type: "warning" })
        return
    }
    postDel(ids.value)
}
// 删除接口
function postDel(params) {
    proxy.$axios
        .post("product/price/delete", {
            price_id: params,
        })
        .then((res) => {
            if (res.data.code == 0) {
                pubParams(getList)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "UpAndDown",
}
</script>

<style lang="less" scoped>
.detail-item {
    line-height: 36px;
    .detail-input {
        line-height: 36px;
        height: 36px;
    }
}
</style>
